package com.lkx.farmershop.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lkx.farmershop.common.api.ApiResult;
import com.lkx.farmershop.mapper.ChatMapper;
import com.lkx.farmershop.model.dto.ChatDto;
import com.lkx.farmershop.model.dto.PrivateChatDto;
import com.lkx.farmershop.model.entity.Chat;
import com.lkx.farmershop.model.entity.Farmer;
import com.lkx.farmershop.model.entity.PrivateChat;
import com.lkx.farmershop.model.vo.ChatVo;
import com.lkx.farmershop.model.vo.PrivateChatVo;
import com.lkx.farmershop.model.vo.SimpleChatVo;
import com.lkx.farmershop.model.vo.SimpleUserVo;
import com.lkx.farmershop.service.ChatService;
import com.lkx.farmershop.service.IFarmerService;
import com.lkx.farmershop.service.PrivateChatService;
import com.lkx.farmershop.service.TuanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * (Chat)表服务实现类
 *
 * @author makejava
 * @since 2025-02-12 15:30:20
 */
@Service("chatService")
public class ChatServiceImpl extends ServiceImpl<ChatMapper, Chat> implements ChatService {

    @Autowired
    private TuanService tuanService;
    @Autowired
    private IFarmerService farmerService;
    @Autowired
    private PrivateChatService privateChatService;

    @Override
    public ApiResult<String> sendMessage(ChatDto chatDto) {
        //判断消息是否为空
        if (chatDto.getMessageContent() == null || chatDto.getMessageContent().isEmpty()) {
            return ApiResult.failed("消息不能为空");
        }

        //保存数据
        save(new Chat(chatDto.getTuanId(), chatDto.getMessageContent(),
                chatDto.getUserId(), LocalDateTime.now()));
        return ApiResult.success("发送成功");
    }

    @Override
    public ApiResult<String> sendPrivateMessage(PrivateChatDto chatDto) {
        //判断消息是否为空
        if (chatDto.getContent() == null || chatDto.getContent().isEmpty()) {
            return ApiResult.failed("消息不能为空");
        }

        privateChatService.save(new PrivateChat(chatDto.getUserId(), chatDto.getTheUserId(),
                chatDto.getContent(), LocalDateTime.now()));
        return ApiResult.success("发送成功");
    }



    @Override
    public ApiResult<List<ChatVo>> getChatList(Long tuanId) {
        List<Chat> chatList = lambdaQuery().eq(Chat::getTuanId, tuanId)
                .orderByAsc(Chat::getSendTime).list();
        //判断是否为空
        if (chatList == null || chatList.isEmpty()) {
            return ApiResult.success(new ArrayList<>());
        }
        //转换为返回值类型
        List<ChatVo> chatVoList = chatList.stream().map(chat -> {
            ChatVo chatVo = new ChatVo(chat.getMessageContent(), chat.getSendTime());
            Farmer user = farmerService.getById(chat.getUserId());
            chatVo.setSimpleUserVo(new SimpleUserVo(user.getFarmerId(), user.getName(), user.getAvatar()));
            return chatVo;
        }).collect(Collectors.toList());

        return ApiResult.success(chatVoList);
    }

    @Override
    public ApiResult<List<ChatVo>> getPrivateChat(Long userId, Long theUserId) {
        List<PrivateChat> chatList = privateChatService.lambdaQuery().eq(PrivateChat::getUserId, userId)
                .eq(PrivateChat::getPartnerId, theUserId).or()
                .eq(PrivateChat::getUserId, theUserId)
                .eq(PrivateChat::getPartnerId, userId)
                .orderByAsc(PrivateChat::getSendTime)
                .list();
        //判断是否为空
        if (chatList == null || chatList.isEmpty()) {
            return ApiResult.success(new ArrayList<>());
        }

        //转换为返回值类型
        List<ChatVo> chatVoList = chatList.stream().map(chat -> {
            ChatVo chatVo = new ChatVo(chat.getContent(), chat.getSendTime());
            Farmer user = farmerService.getById(chat.getUserId());
            chatVo.setSimpleUserVo(new SimpleUserVo(user.getFarmerId(), user.getName(), user.getAvatar()));
            return chatVo;
        }).collect(Collectors.toList());

        return ApiResult.success(chatVoList);
    }

    @Override
    public ApiResult<List<SimpleChatVo>> getAllChat(Long userId) {
        //查询所有群聊
        List<Chat> chatList = lambdaQuery().eq(Chat::getUserId, userId)
                .orderByAsc(Chat::getSendTime).list();
        //去除属于相同tuanId的chat，只保留sendTime最新的一个
        Map<Long, Chat> latestChats = chatList.stream()
                .collect(Collectors.toMap(
                        Chat::getTuanId,
                        chat -> chat,
                        (existing, replacement) -> existing.getSendTime().isBefore(replacement.getSendTime()) ? replacement : existing
                ));

        //转换为返回值类型
        List<SimpleChatVo> simpleChatVoList = latestChats.values().stream()
                .map(chat -> new SimpleChatVo(chat.getTuanId(),
                        tuanService.getById(chat.getTuanId()).getTuanTitle(),
                        chat.getMessageContent())).collect(Collectors.toList());

        return ApiResult.success(simpleChatVoList);
    }

    @Override
    public ApiResult<List<PrivateChatVo>> getAllPrivateChat(Long userId) {
        List<PrivateChat> chatList = privateChatService.lambdaQuery().eq(PrivateChat::getUserId, userId)
                .or().eq(PrivateChat::getPartnerId, userId)
                .orderByAsc(PrivateChat::getSendTime)
                .list();

        chatList.forEach(chat -> {
            if (chat.getPartnerId().equals(userId)) {
                Long PartnerId = chat.getUserId();
                chat.setUserId(chat.getPartnerId());
                chat.setPartnerId(PartnerId);
            }
        });

        //去重
        Map<Long, PrivateChat> latestChats = chatList.stream()
                .collect(Collectors.toMap(
                        PrivateChat::getPartnerId,
                        chat -> chat,
                        (existing, replacement) -> existing.getSendTime().isBefore(replacement.getSendTime()) ? replacement : existing
                ));
        //转换为返回值类型
        List<PrivateChatVo> privateChatVoList = latestChats.values().stream()
                .map(chat -> {
                    Farmer user = farmerService.getById(chat.getPartnerId());
                    return new PrivateChatVo(new SimpleUserVo(user.getFarmerId(), user.getName(), user.getAvatar()), chat.getContent());
                }).collect(Collectors.toList());

        return ApiResult.success(privateChatVoList);
    }

}

